package com.base.git;

import org.eclipse.jgit.api.*;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.revwalk.*;
import org.eclipse.jgit.revwalk.filter.*;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import java.io.File;

public class GitHistoryDemo {

    public static void main(String[] args) throws Exception {
        // 指定本地仓库目录路径
        String localRepositoryPath = "D:\\java\\work\\base-demo";

        // 打开本地仓库
        Repository repository = new FileRepositoryBuilder()
                .setGitDir(new File(localRepositoryPath + "/.git"))
                .build();

        // 创建 Git 对象
        Git git = new Git(repository);

        // 使用 RevWalk 遍历提交历史
        try (RevWalk walk = new RevWalk(repository)) {
            Ref head = repository.exactRef(Constants.HEAD);

            // 从头部引用获取提交对象
            RevCommit commit = walk.parseCommit(head.getObjectId());

            System.out.println("Commit History:");

            // 遍历提交历史
            walk.markStart(commit);
            for (RevCommit revCommit : walk) {
                System.out.println(revCommit.getFullMessage());
            }
        }

        // 关闭 Git 和 Repository 对象
        git.close();
        repository.close();
    }
}